package smsverificationci;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.Properties;

@SpringBootApplication
@RestController
@RequestMapping(value = "/test")
public class TestVerification {

    public static void main(String[] args){
        SpringApplication.run(TestVerification.class);
    }

    @Autowired
    private IpConfiguration ipConfiguration;

    @GetMapping(value = "/captchatest",produces = "application/json")
    public void testCaptcha(HttpServletResponse response) throws IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");
        Properties properties = new Properties();
        properties.put("kaptcha.border", "no");//是否存在边框
        properties.put("kaptcha.textproducer.char.length","4");//验证码长度
        properties.put("kaptcha.textproducer.font.color","blue");//字体颜色
        properties.put("kaptcha.textproducer.char.space","10");//字体间距
        //properties.put("kaptcha.noise.impl","com.google.code.kaptcha.impl.NoNoise");//是否存在干扰线
        properties.put("kaptcha.background.clear.from","white");//背景颜色渐变色开始
        properties.put("kaptcha.background.clear.to","white");//背景颜色渐变色结束
        Config config = new Config(properties);
        DefaultKaptcha kaptcha = new DefaultKaptcha();
        kaptcha.setConfig(config);
        String text = kaptcha.createText();
        System.out.println(text);
        BufferedImage image = kaptcha.createImage(text);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
        IOUtils.closeQuietly(out);

    }

    public void testResponse(){
        try{

            URL url = new URL("http://localhost:"+ipConfiguration.getPort()+"/captchatest");
            URLConnection connection = url.openConnection();
            InputStream inputStream = connection.getInputStream();
            File file = new File("a.jpeg");
            while(true){
                int read = inputStream.read();
                System.out.print((char)read);
                if (read == -1) break;

            }


        }catch (Exception e){
            e.printStackTrace();
        }



    }
}
